package com.imxinxin.common.tools.http;


import com.imxinxin.common.model.KVEntry;
import com.imxinxin.common.tools.io.InputStreamTool;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;


/**
 * @Author: Eisen
 * @Create_Date: 2019-03-01 HTTP调用工具
 **/
public class HttpSend {

    public static final String CONTENT_TYPE = "Content-type";

//    public static final Gson gson = new GsonBuilder().disableHtmlEscaping().create();

//    public static CookieManager manager;


//    static {
//        HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier());
//        SSLContext ctx = null;
//        try {
//            ctx = SSLContext.getInstance("TLS");
//        } catch (NoSuchAlgorithmException e) {
//            e.printStackTrace();
//        }
//        try {
//            ctx.init(null, trustManagers, new SecureRandom());
//        } catch (KeyManagementException e) {
//            e.printStackTrace();
//        }
//        HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
//
////        manager = new CookieManager();
////        manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
////        CookieHandler.setDefault(manager);
//
//    }

    /**
     * 全参数http调用 用于接口请求 不用于下载文件
     */
    public static HttpResult request(HttpConfig httpConfig) throws IOException {


        HttpURLConnection http = null;
        OutputStream out = null;
        try {
            URL url = new URL(httpConfig.getUrlPath());
            // 打开连接
            if (httpConfig.getProxy() == null) {
                http = (HttpURLConnection) url.openConnection();
            } else {
                http = (HttpURLConnection) url.openConnection(httpConfig.getProxy());
            }
            // post请求
            http.setRequestMethod(httpConfig.getRequestMethod());
            // 连接超时时间
            http.setConnectTimeout(httpConfig.getConnectTimeout());
            // 读取数据超时时间
            http.setReadTimeout(httpConfig.getReadTimeout());
            // 禁用缓存
            http.setUseCaches(httpConfig.isUseCaches());
            // 允许向sever写数据
            http.setDoOutput(true);
            // 允许读数据 http.setDoInput(true);
//            http.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36");
            // 传入格式
//            http.setRequestProperty(CONTENT_TYPE, httpConfig.getContentType() + ";charset=" + httpConfig.getSendCharset());

            // 可以设置header cookie等
            if (httpConfig.getHeaders() != null) {
                for (KVEntry<String, String> kv : httpConfig.getHeaders()) {
                    http.setRequestProperty(kv.key, kv.value);
                }
            }

            //请求送的数据
            if (httpConfig.getSendBytes() != null) {
                out = http.getOutputStream();
                out.write(httpConfig.getSendBytes());
                out.flush();
            }
//            http.connect();
            int code = http.getResponseCode();
            HttpResult httpResult = new HttpResult();
            httpResult.setResponseCode(code);
            httpResult.setResponseMessage(http.getResponseMessage());
            httpResult.setHeaderFields(http.getHeaderFields());


            //请求出错处理
            if (code != HttpURLConnection.HTTP_OK) {
                //读取错误信息
                if (http.getErrorStream() != null) {
                    httpResult.setResponseErrorBody(InputStreamTool.inputStreamToBytes(http.getErrorStream()));
                    httpResult.setResponseErrorMessage(new String(httpResult.getResponseErrorBody(), httpConfig.getReadCharset()));
                }
                return httpResult;
            }

            InputStream inputStream = http.getInputStream();

            //如果没有输入流直接返回
            if (inputStream == null) {
                return httpResult;
            }

            switch (httpConfig.getResultType()) {
                case STRING:
                    httpResult.setResponseString(InputStreamTool.inputStreamToString(inputStream, httpConfig.getReadCharset()));
                    break;
                case FILE:
                    httpResult.setResponseFilePath(InputStreamTool.inputStreamToFile(inputStream, httpConfig.getFilePath(), httpConfig.getFileName()));
                    break;
                case BYTES:
                    httpResult.setResponseBody(InputStreamTool.inputStreamToBytes(inputStream));
            }

            return httpResult;

        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } finally {
                if (http != null) {
                    http.disconnect();
                }
            }
        }

    }


}
